<?php

namespace app\admin\model\finance;

use think\Model;
use traits\model\SoftDelete;

class Incomelog extends Model
{

    use SoftDelete;

    // 表名
    protected $name = 'finance_income_log';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'datatime_text',
        'audittime_text',
        'status_text'
    ];

    protected static function init()
    {
        self::afterInsert(function ($row) {
            $pk = $row->getPk();
            $row->getQuery()->where($pk, $row[$pk])->update(['create_id' => \think\Session::get('admin.id')]);
        });

        self::afterUpdate(function ($row) {
            if ($row->status == 'audited') {
                $pk = $row->getPk();
                $row->getQuery()->where($pk, $row[$pk])->update(['audittime' => time(), 'audit_id' => \think\Session::get('admin.id')]);
            }
        });
    }

    public function getStatusList()
    {
        return ['unaudited' => __('Unaudited'), 'audited' => __('Audited')];
    }


    public function getDatatimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['datatime']) ? $data['datatime'] : '');
        return is_numeric($value) ? date("Y-m-d", $value) : $value;
    }


    public function getAudittimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['audittime']) ? $data['audittime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    protected function setDatatimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setAudittimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


    public function admin()
    {
        return $this->belongsTo('app\admin\model\Admin', 'create_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function audit()
    {
        return $this->belongsTo('app\admin\model\Admin', 'audit_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function group()
    {
        return $this->belongsTo('app\admin\model\AuthGroup', 'group_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function subjects()
    {
        return $this->belongsTo('Subjects', 'subjects_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function type()
    {
        return $this->belongsTo('app\admin\model\finance\Income', 'type_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
}
